﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;

namespace PlatWL.Services.Tools
{
    public class Common
    {
        #region 生成图片验证码
        /// <summary>
        /// 创建验证码的图片,输出流
        /// </summary>
        /// <param name="containsPage">要输出到的page对象</param>
        /// <param name="validateNum">验证码</param>
        public static byte[] CreateValidateGraphic(string validateCode)
        {
            Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0) + 10, 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的干扰线
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
                 Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(validateCode, font, brush, 3, 2);
                //画图片的前景干扰点
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                //保存图片数据
                MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                //输出图片流
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
        #endregion

        #region 生成随机数
        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="VcodeNum">位数</param>
        /// <returns></returns>
        public static string RndNum(int VcodeNum)
        {
            string Vchar = "0,1,2,3,4,5,6,7,8,9";
            string[] VcArray = Vchar.Split(",".ToCharArray());
            string VNum = "";
            System.Random ro = new Random();
            for (int i = 1; i <= VcodeNum; i++)
            {
                int decA = ro.Next(0, 10);
                VNum = VNum + VcArray[decA];
            }

            return VNum;
        }
        public static string RndNum2(int VcodeNum)
        {
            string Vchar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
            string[] VcArray = Vchar.Split(",".ToCharArray());
            int length = VcArray.Length;
            string VNum = "";
            System.Random ro = new Random();
            for (int i = 1; i <= VcodeNum; i++)
            {
                int decA = ro.Next(0, length);
                VNum = VNum + VcArray[decA];
            }

            return VNum;
        }
        #endregion

        #region GUID
        public static string GuID()
        {
            return Md5(Guid.NewGuid().ToString() + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }
        #endregion

        #region 数据表转换为list，泛型
        public static List<T> GetTableToList<T>(DataTable table)
        {
            List<T> list = new List<T>();
            T t = default(T);
            PropertyInfo[] propertypes = null;
            string tempName = string.Empty;
            foreach (DataRow row in table.Rows)
            {
                t = Activator.CreateInstance<T>();
                propertypes = t.GetType().GetProperties();
                foreach (PropertyInfo pro in propertypes)
                {
                    tempName = pro.Name;
                    if (table.Columns.Contains(tempName))
                    {
                        object value = row[tempName];
                        if (!value.ToString().Equals(""))
                        {
                            pro.SetValue(t, value, null);
                        }
                    }
                }
                list.Add(t);
            }
            return list;
        }
        #endregion

        #region 去除HTML标记
        /// <summary>
        /// 去除HTML标记
        /// </summary>
        /// <param name="Htmlstring">字符串</param>
        /// <returns>过滤后的串</returns>
        public static string NoHTML(string Htmlstring, int length = 0) //去除HTML标记
        {
            if (!string.IsNullOrEmpty(Htmlstring))
            {
                #region OLD
                //删除脚本
                //Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
                ////删除HTML
                //Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
                //Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
                //Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
                //Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

                //Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
                //Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
                //Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
                //Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
                //Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
                //Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
                //Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
                //Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
                //Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
                //Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

                //Htmlstring.Replace("<", "");
                //Htmlstring.Replace(">", "");
                //Htmlstring.Replace("\r\n", "");
                //Htmlstring = Htmlstring.Replace("[\\s]{2,{", " ");
                //Htmlstring = Htmlstring.Replace("( <[b|B][r|R]/*>)+|( <[p|P](.|\\n)*?>)", "\n"); // <br> 
                //Htmlstring = Htmlstring.Replace("(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " "); //&nbsp; 
                //Htmlstring = Htmlstring.Replace(" <(.|\\n)*?>", string.Empty); //any other tags 
                //Htmlstring = Htmlstring.Replace("\r\n", "<br>");
                //Htmlstring = Htmlstring.Replace("=", "");
                //Htmlstring = Htmlstring.Replace("%", "");
                //Htmlstring = Htmlstring.Replace("'", "");
                //Htmlstring = Htmlstring.Replace("select ", "");
                //Htmlstring = Htmlstring.Replace("insert ", "");
                //Htmlstring = Htmlstring.Replace("delete ", "");
                //Htmlstring = Htmlstring.Replace(" or", "");
                //Htmlstring = Htmlstring.Replace("exec ", "");
                //Htmlstring = Htmlstring.Replace("--", "");
                //Htmlstring = Htmlstring.Replace(" and", "");
                //Htmlstring = Htmlstring.Replace(" AND", "");
                //Htmlstring = Htmlstring.Replace(" And", "");
                //Htmlstring = Htmlstring.Replace(" AnD", "");
                //Htmlstring = Htmlstring.Replace(" ANd", "");
                //Htmlstring = Htmlstring.Replace(" aND", "");
                //Htmlstring = Htmlstring.Replace(" aNd", "");
                //Htmlstring = Htmlstring.Replace(" anD", "");
                //Htmlstring = Htmlstring.Replace("where ", "");
                //Htmlstring = Htmlstring.Replace("update ", "");
                //Htmlstring = Htmlstring.Replace("script", "");
                //Htmlstring = Htmlstring.Replace("iframe", "");
                //Htmlstring = Htmlstring.Replace("master", "");
                //Htmlstring = Htmlstring.Replace("&nbsp;", "");
                //Htmlstring = Htmlstring.Replace("exec ", "");
                //Htmlstring = Htmlstring.Replace("exists", "");
                //Htmlstring = Htmlstring.Replace("drop", "");
                //Htmlstring = Htmlstring.Replace("996008E", "");
                //Htmlstring = Htmlstring.Replace("ar(124)", "");
                //Htmlstring = Htmlstring.Replace("1and", "");
                //Htmlstring = Htmlstring.Replace("0and", "");
                //Htmlstring = Htmlstring.Replace("chr(", "");

                //Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
                #endregion

                if (string.IsNullOrEmpty(Htmlstring)) return Htmlstring;
                Regex regex = new Regex("<.+?>");
                var matches = regex.Matches(Htmlstring);

                foreach (Match match in matches)
                {
                    Htmlstring = Htmlstring.Replace(match.Value, "");
                }
                if (length == 0) //返回全部
                {
                    return Htmlstring;
                }
                else
                {
                    return Htmlstring.Length > length ? Htmlstring.Substring(0, length) : Htmlstring;
                }
            }
            return Htmlstring;
        }

        /// <summary>
        /// 去除HTML标记,如果对象为null,返回"0"
        /// </summary>
        /// <param name="Htmlstring">对象</param>
        /// <returns>过滤后的串</returns>
        public static string NoHTML1(object Htmlstring) //去除HTML标记
        {
            if (Htmlstring == null)
            {
                return "0";
            }
            return NoHTML(Htmlstring.ToString());
        }
        #endregion

        #region 获取访问者ip
        public static string GetIP()
        {
            string result = String.Empty;
            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (result != null && result != String.Empty)
            {
                //可能有代理
                if (result.IndexOf(".") == -1)    //没有“.”肯定是非IPv4格式
                    result = null;
                else
                {
                    if (result.IndexOf(",") != -1)
                    {
                        //有“,”，估计多个代理。取第一个不是内网的IP。
                        result = result.Replace(" ", "").Replace("'", "");
                        string[] temparyip = result.Split(",;".ToCharArray());
                        for (int i = 0; i < temparyip.Length; i++)
                        {
                            if (IsIPAddress(temparyip[i])
                                && temparyip[i].Substring(0, 3) != "10."
                                && temparyip[i].Substring(0, 7) != "192.168"
                                && temparyip[i].Substring(0, 7) != "172.16.")
                            {
                                return temparyip[i];    //找到不是内网的地址
                            }
                        }
                    }
                    else if (IsIPAddress(result)) //代理即是IP格式 ,IsIPAddress判断是否是IP的方法,
                        return result;
                    else
                        result = null;    //代理中的内容 非IP，取IP
                }

            }

            string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (null == result || result == String.Empty)
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (result == null || result == String.Empty)
                result = HttpContext.Current.Request.UserHostAddress;

            return result;

        }
        private static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;

            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";

            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }
        public static string GetIPNum()
        {
            return GetIPNum(GetIP());
        }
        public static string GetIPNum(string ip)
        {
            long num = 0;
            if (!string.IsNullOrEmpty(ip))
            {
                string[] ips = ip.Split('.');
                if (ips.Length == 4)
                {
                    long num1 = long.Parse(ips[0]) * 256 * 256 * 256;
                    long num2 = long.Parse(ips[1]) * 256 * 256;
                    long num3 = long.Parse(ips[2]) * 256;
                    long num4 = long.Parse(ips[3]);
                    num = num1 + num2 + num3 + num4;
                }
            }
            return num.ToString();
        }

        #endregion

        #region 发送邮件
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="fromAddress">发信邮箱账号</param>
        /// <param name="fromAddressPwd">发信邮箱账号密码</param>
        /// <param name="toAddress">收信邮箱地址</param>
        /// <param name="title">邮件标题</param>
        /// <param name="content">邮件内容</param>
        /// <returns></returns>
        public static bool SendMail(string fromAddress, string fromAddressPwd, string toAddress, string title, string content)
        {
            MailAddress to = new MailAddress(toAddress);//接收者邮箱
            MailAddress from = new MailAddress(fromAddress);//发送者邮箱
            MailMessage mail = new MailMessage(from, to);
            mail.Subject = title;
            mail.IsBodyHtml = true;
            mail.Body = content;
            SmtpClient client = new SmtpClient();
            client.Host = "smtp.exmail.qq.com";//设置发送者邮箱对应的smtpserver
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(fromAddress, fromAddressPwd);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            try
            {
                client.Send(mail);
                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="fromAddress">发信邮箱账号</param>
        /// <param name="fromAddressPwd">发信邮箱账号密码</param>
        /// <param name="toAddress">收信邮箱地址</param>
        /// <param name="title">邮件标题</param>
        /// <param name="content">邮件内容</param>
        /// <returns></returns>
        public static bool SendMail(string toAddress, string title, string content)
        {
            string fromAddress = "yfzsb@zhenshiyuan.com";
            string fromAddressPwd = "jiubugaosuNI2015";
            MailAddress to = new MailAddress(toAddress);//接收者邮箱
            MailAddress from = new MailAddress(fromAddress);//发送者邮箱
            MailMessage mail = new MailMessage(from, to);
            mail.Subject = title;
            mail.IsBodyHtml = true;
            mail.Body = content;
            SmtpClient client = new SmtpClient();
            client.Host = "smtp.exmail.qq.com";//设置发送者邮箱对应的smtpserver
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(fromAddress, fromAddressPwd);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            try
            {
                client.Send(mail);
                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }

        #endregion

        #region MD5加密
        /// <summary>
        /// MD5加密，截取
        /// </summary>
        /// <param name="source">加密字符</param>
        /// <returns></returns>
        public static string Md5(string source)
        {
            if (string.IsNullOrEmpty(source))
                return string.Empty;

            string result = "tx001";
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(source));

            result = BitConverter.ToString(s).Replace("-", string.Empty);
            return result.ToLower();

        }
        #endregion

        #region discuz论坛cookie解析
        public static string GetUserName(HttpContextBase httpContextBase, string cookieName)
        {
            string str = "";
            if (httpContextBase != null)
            {
                if (httpContextBase.Request.Cookies[cookieName] != null)
                {
                    HttpCookie hc = httpContextBase.Request.Cookies[cookieName];
                }
            }
            return str;
        }
        #endregion

        #region 浏览器型号

        /// <summary>
        /// 获取访问者浏览器
        /// </summary>
        /// <param name="agent"></param>
        /// <returns></returns>
        public static int GetSoft(string agent)
        {
            int soft = 0;
            if (agent.Contains("NetCaptor"))
            {
                soft = 1;
            }
            else if (agent.Contains("Firefox"))
            {
                soft = 2;
            }
            else if (agent.Contains("Opera"))
            {
                soft = 3;
            }
            else if (agent.Contains("Safari"))
            {
                soft = 4;
            }
            else if (agent.Contains("Chrome"))
            {
                soft = 5;
            }
            else if (agent.Contains("MSIE 6"))
            {
                soft = 6;
            }
            else if (agent.Contains("MSIE 7"))
            {
                soft = 7;
            }
            else if (agent.Contains("MSIE 8"))
            {
                soft = 8;
            }
            else if (agent.Contains("MSIE 9"))
            {
                soft = 9;
            }
            else if (agent.Contains("MSIE 10"))
            {
                soft = 10;
            }
            else if (agent.Contains("MSIE 11"))
            {
                soft = 11;
            }
            return soft;
        }

        #endregion

        #region 系统型号

        /// <summary>
        /// 获取浏览者系统
        /// </summary>
        /// <param name="agent"></param>
        /// <returns></returns>
        public static int GetOS(string agent)
        {
            int os = 0;
            if (agent.Contains("Windows NT 5.0"))
            {
                os = 1;
            }
            else if (agent.Contains("Windows NT 5.1"))
            {
                os = 2;
            }
            else if (agent.Contains("Windows NT 6.1"))
            {
                os = 3;
            }
            else if (agent.Contains("unix") || agent.Contains("linux") || agent.Contains("SunOS") || agent.Contains("BSD"))
            {
                os = 4;
            }
            else if (agent.Contains("Mac"))
            {
                os = 5;
            }
            return os;
        }
        #endregion

        #region 同步post页面
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pageUrl">请求页面</param>
        /// <returns>json格式数据</returns>
        public static string GetResponseData(string pageUrl)
        {
            return GetResponseData(pageUrl, "POST", new Dictionary<string, string>());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pageUrl">请求页面</param>
        /// <returns>json格式数据</returns>
        public static string GetResponseData(string pageUrl, string method, Dictionary<string, string> dic)
        {
            string strResult = "";
            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(pageUrl);
                // myRequest.Referer = "http://www.cooju.cn/";
                foreach (string item in dic.Keys)
                {
                    myRequest.Headers.Add(item, dic[item]);
                }
                myRequest.Method = method;
                myRequest.ContentType = "application/x-www-form-urlencoded";
                try
                {
                    HttpWebResponse HttpWResp = (HttpWebResponse)myRequest.GetResponse();
                    Stream myStream = HttpWResp.GetResponseStream();
                    StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
                    StringBuilder strBuilder = new StringBuilder();
                    while (-1 != sr.Peek())
                    {
                        strBuilder.Append(sr.ReadLine());
                    }
                    strResult = strBuilder.ToString();
                }
                catch (Exception exp)
                {
                    strResult = "{\"error\":\"false\",\"error_description\":\"" + exp.Message + "\"}";
                }
            }
            catch (Exception exp)
            {
                strResult = "{\"error\":\"false\",\"error_description\":\"" + exp.Message + "\"}";
            }
            return strResult;
        }
        #endregion

        #region 异步post页面
        public static void GetResponseAsync(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "GET";
            request.GetResponse();
            //request.GetResponseAsync();
        }
        #endregion

        #region 获取页面内容
        public static string GetUrlContent(string uri, string method, Dictionary<string, string> headers)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = method;
            if (headers != null)
            {
                foreach (KeyValuePair<string, string> headersKey in headers)
                {
                    request.Headers.Add(headersKey.Key, headersKey.Value);
                }
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
            string respHtml;
            try
            {
                respHtml = reader.ReadToEnd();
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                reader.Close();
            }
            return respHtml;

        }

        public static string GetUrlContent(string url)
        {
            return GetUrlContent(url, new Dictionary<string, string>());
        }
        public static string GetUrlContent(string url, Dictionary<string, string> dic)
        {
            WebClient wc = new WebClient();
            wc.Credentials = CredentialCache.DefaultCredentials;
            wc.Encoding = Encoding.UTF8;

            foreach (KeyValuePair<string, string> item in dic)
            {
                wc.Headers.Add(item.Key, item.Value);
            }
            string returnText = wc.DownloadString(url);
            return returnText;
        }
        #endregion

        #region 异步post页面，json参数
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Url">请求页面</param>
        /// <param name="JSONData">请求json参数</param>
        /// <returns>json格式数据</returns>
        public static string GetResponseData(string JSONData, string Url)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(JSONData);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentLength = bytes.Length;
            request.ContentType = "text/xml";
            // request.Referer = "http://www.cooju.cn/";
            Stream reqstream = request.GetRequestStream();
            reqstream.Write(bytes, 0, bytes.Length);

            //声明一个HttpWebRequest请求  
            request.Timeout = 90000;
            //设置连接超时时间  
            request.Headers.Set("Pragma", "no-cache");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamReceive = response.GetResponseStream();
            Encoding encoding = Encoding.UTF8;

            StreamReader streamReader = new StreamReader(streamReceive, encoding);
            string strResult = streamReader.ReadToEnd();
            streamReceive.Dispose();
            streamReader.Dispose();

            return strResult;
        }
        #endregion

        #region POST上传文件
        public static string HttpPostFile(string uploadUrl, string fileToUpload, string poststr = "")
        {
            string result = "";

            try
            {
                string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
                HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uploadUrl);
                webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
                webrequest.Method = "POST";
                StringBuilder sb = new StringBuilder();
                if (poststr != "")
                {
                    foreach (string c in poststr.Split('&'))
                    {
                        string[] item = c.Split('=');
                        if (item.Length != 2)
                        {
                            break;
                        }
                        string name = item[0];
                        string value = item[1];
                        sb.Append("–" + boundary);
                        sb.Append("\r\n");
                        sb.Append("Content-Disposition: form-data; name=\"" + name + "\"");
                        sb.Append("\r\n\r\n");
                        sb.Append(value);
                        sb.Append("\r\n");
                    }
                }
                sb.Append("--");
                sb.Append(boundary);
                sb.Append("\r\n");
                sb.Append("Content-Disposition: form-data; name=\"file");
                //sb.Append(fileFormName);
                sb.Append("\"; filename=\"");
                sb.Append(Path.GetFileName(fileToUpload));
                sb.Append("\"");
                sb.Append("\r\n");
                sb.Append("Content-Type: application/octet-stream");
                //sb.Append(contenttype);
                sb.Append("\r\n");
                sb.Append("\r\n");
                string postHeader = sb.ToString();
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
                byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                FileStream fileStream = new FileStream(fileToUpload, FileMode.Open, FileAccess.Read);
                long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
                webrequest.ContentLength = length;
                Stream requestStream = webrequest.GetRequestStream();
                requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                byte[] buffer = new Byte[(int)fileStream.Length];
                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }
                requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                fileStream.Close();
                WebResponse responce = webrequest.GetResponse();
                requestStream.Close();
                using (Stream s = responce.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(s))
                    {
                        result = sr.ReadToEnd();
                    }
                }

            }
            catch (Exception ex)
            {
                //CommonHelp.WriteLOG(uploadUrl + "|||" + fileToUpload + "|||" + ex.ToString());
            }
            return result;
        }
        public static string PostByte(string url, string method, string param)
        {
            //转换输入参数的编码类型，获取bytep[]数组 
            byte[] byteArray = Encoding.UTF8.GetBytes("json=" + param);
            //初始化新的webRequst
            //1． 创建httpWebRequest对象
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url + "/" + method));
            //2． 初始化HttpWebRequest对象
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = byteArray.Length;
            //3． 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊，它并没有提供一个属性给用户存取，需要写入HttpWebRequest对象提供的一个stream里面。)
            Stream newStream = webRequest.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面
            newStream.Write(byteArray, 0, byteArray.Length);
            newStream.Close();
            //4． 读取服务器的返回信息
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string phpend = php.ReadToEnd();
            return phpend;

        }
        #endregion

        #region 判断是否手机访问
        public static bool IsMobile(string agent)
        {
            bool result = false;
            string sUserAgent = agent.ToLower();

            if (sUserAgent.Contains("ipad") || sUserAgent.Contains("iphone") || sUserAgent.Contains("midp") || sUserAgent.Contains("rv:1.2.3.4") || sUserAgent.Contains("ucweb") || sUserAgent.Contains("android") || sUserAgent.Contains("windows ce") || sUserAgent.Contains("windows mobile"))
            {
                result = true;
            }
            return result;
        }
        #endregion

        #region 判断是否微信
        public static bool IsWeiXin(string useragent)
        {
            if (!string.IsNullOrEmpty(useragent))
            {
                return useragent.ToLower().Contains("micromessenger");
            }
            return false;
        }
        #endregion

        #region 获取资料添加时间为多久前
        public static string GetTimeGo(string createtime)
        {
            DateTime create = Convert.ToDateTime(createtime);
            DateTime Now = DateTime.Now;
            TimeSpan ts = Now - create;
            string str = "";
            var days = ts.Days;
            if (days > 0)
            {
                str = days + "天前";
            }
            else
            {
                var hour = ts.Hours;
                if (hour > 0)
                {
                    str = hour + "小时前";
                }
                else
                {
                    var Minute = ts.Minutes;
                    if (Minute > 0)
                    {
                        str = Minute + "分钟前";
                    }
                    else
                    {
                        var secend = ts.Seconds;
                        if (secend > 0)
                        {
                            str = secend + "秒前";
                        }
                    }
                }
            }
            return str;
        }
        #endregion

        #region 截取字符串
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <param name="length">截取长度</param>
        /// <param name="type">0加…… 1不加</param>
        /// <returns></returns>
        public static string GetSubstring(string str, int length, int type)
        {
            string returnStr = "";
            if (!string.IsNullOrEmpty(str))
            {

                if (str.Length >= length)
                {
                    returnStr = str.Substring(0, length);
                    if (type == 0)
                    {
                        returnStr += "……";
                    }
                }
                else
                {
                    returnStr = str;
                }
            }
            return returnStr;

        }
        #endregion

        #region 写txt日志文件
        public static void WriteLog(string errorMessage)
        {
            try
            {
                string logFile = System.Web.HttpRuntime.AppDomainAppPath + "LOG";

                //string logFile = HttpContext.Current.Server.MapPath("/LOG/") + DateTime.Now.ToString("yyyyMMdd") + ".log";

                if (!Directory.Exists(logFile))
                {
                    Directory.CreateDirectory(logFile);
                }
                //if (!File.Exists(logFile))
                //{
                //    File.Create(logFile);
                //}
                logFile += "/" + DateTime.Now.ToString("yyyyMMdd") + ".log";
                FileStream fs = new FileStream(logFile, FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine();
                if (HttpContext.Current != null)
                {
                    sw.WriteLine(HttpContext.Current.Request.Url.AbsoluteUri);
                }
                sw.WriteLine(errorMessage);
                sw.WriteLine("执行时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                sw.WriteLine();
                sw.Close();
                fs.Close();
            }
            catch (Exception ex)
            {

            }

        }
        #endregion

        #region 数字转英文字母

        /// <summary>
        /// 获取大写英文字母
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static string GetEnglish(int i)
        {
            string str = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
            return str.Substring(i - 1, 1);
        }
        #endregion

        #region 访问浏览器下载并保存文件
        public static void SaveWebFile(string url, string fileType, string saveFilePath, string saveFileName)
        {
            WebClient wc = new WebClient();
            string path = HttpContext.Current.Server.MapPath(saveFilePath);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            wc.DownloadFile(url, path + saveFileName);

        }
        #endregion

        #region 流下载
        public static void DownLoadFile(HttpContextBase page, string filename)
        {
            string filepath = page.Server.MapPath(filename);
            string fileExt = Path.GetExtension(filepath);
            string savefilename = DateTime.Now.ToString("yyyyMMddHHmmss");

            FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();

            page.Response.Clear();
            page.Response.Charset = "UTF-8";
            string str = "text/html";
            switch (fileExt.Substring(1).ToLower())
            {
                #region 文件头对应的页面格式

                case "doc": str = "application/msword"; break;
                case "pdf": str = "application/pdf"; break;
                case "zip": str = "application/zip"; break;
                case "xls": str = "application/vnd.ms-excel"; break;
                case "xml": str = "text/xml"; break;
                case "mpeg": str = "video/mpeg"; break;
                case "mpg": str = "video/mpeg"; break;
                case "gif": str = "image/gif"; break;
                case "jpeg": str = "image/jpeg"; break;
                case "jpg": str = "image/jpeg"; break;
                case "jpe": str = "image/jpeg"; break;
                case "txt": str = "text/plain"; break;
                case "html": str = "text/html"; break;
                case "png": str = "image/png"; break;
                    //                case "ez":str= "application/andrew-inset";break;
                    //case "hqx" : str= "application/mac-binhex40";break; 
                    //case "cpt" : str= "application/mac-compactpro";break; 
                    //case "bin" : str= "application/octet-stream";break; 
                    //case "dms" : str= "application/octet-stream";break; 
                    //case "lha" : str= "application/octet-stream";break;
                    //case "ief": str = "image/ief"; break;
                    //case "lzh": str = "application/octet-stream"; break; 
                    //case "exe" : str= "application/octet-stream";break; 
                    //case "class" : str= "application/octet-stream";break; 
                    //case "so" : str= "application/octet-stream";break; 
                    //case "dll" : str= "application/octet-stream";break; 
                    //case "oda" : str= "application/oda";break; 
                    //case "ai" : str= "application/postscript";break; 
                    //case "eps" : str= "application/postscript";break; 
                    //case "ps" : str= "application/postscript";break; 
                    //case "smi" : str= "application/smil";break; 
                    //case "smil" : str= "application/smil";break; 
                    //case "mif" : str= "application/vnd.mif";break; 
                    //case "ppt" : str= "application/vnd.ms-powerpoint";break; 
                    //case "wbxml" : str= "application/vnd.wap.wbxml";break; 
                    //case "wmlc" : str= "application/vnd.wap.wmlc";break; 
                    //case "wmlsc" : str= "application/vnd.wap.wmlscriptc";break; 
                    //case "bcpio" : str= "application/x-bcpio";break; 
                    //case "vcd" : str= "application/x-cdlink";break; 
                    //case "pgn" : str= "application/x-chess-pgn";break; 
                    //case "cpio" : str= "application/x-cpio";break; 
                    //case "csh" : str= "application/x-csh";break; 
                    //case "dcr" : str= "application/x-director";break; 
                    //case "dir" : str= "application/x-director";break; 
                    //case "dxr" : str= "application/x-director";break; 
                    //case "dvi" : str= "application/x-dvi";break; 
                    //case "spl" : str= "application/x-futuresplash";break; 
                    //case "gtar" : str= "application/x-gtar";break; 
                    //case "hdf" : str= "application/x-hdf";break; 
                    //case "js" : str= "application/x-javascript";break; 
                    //case "skp" : str= "application/x-koan";break; 
                    //case "skd" : str= "application/x-koan";break; 
                    //case "skt": str="application/x-koan";break; 
                    //case "skm": str= "application/x-koan";break; 
                    //case "latex": str= "application/x-latex";break; 
                    //case "nc": str= "application/x-netcdf";break; 
                    //case "cdf": str= "application/x-netcdf";break; 
                    //case "sh": str= "application/x-sh";break; 
                    //case "shar": str= "application/x-shar";break; 
                    //case "swf": str= "application/x-shockwave-flash";break; 
                    //case "sit": str= "application/x-stuffit";break; 
                    //case "sv4cpio": str= "application/x-sv4cpio";break; 
                    //case "sv4crc": str= "application/x-sv4crc";break; 
                    //case "tar": str= "application/x-tar";break; 
                    //case "tcl": str= "application/x-tcl";break; 
                    //case "tex": str= "application/x-tex";break; 
                    //case "texinfo": str= "application/x-texinfo";break; 
                    //case "texi": str= "application/x-texinfo";break; 
                    //case "t": str= "application/x-troff";break; 
                    //case "tr": str= "application/x-troff";break; 
                    //case "roff": str= "application/x-troff";break; 
                    //case "man": str= "application/x-troff-man";break; 
                    //case "me": str= "application/x-troff-me";break; 
                    //case "ms": str= "application/x-troff-ms";break; 
                    //case "ustar": str= "application/x-ustar";break; 
                    //case "src": str= "application/x-wais-source";break; 
                    //case "xhtml": str= "application/xhtml+xml";break; 
                    //case "xht": str= "application/xhtml+xml";break; 
                    //case "au": str= "audio/basic";break; 
                    //case "snd": str= "audio/basic";break; 
                    //case "mid": str= "audio/midi";break; 
                    //case "midi": str= "audio/midi";break; 
                    //case "kar": str= "audio/midi";break; 
                    //case "mpga": str= "audio/mpeg";break; 
                    //case "mp2": str= "audio/mpeg";break; 
                    //case "mp3": str= "audio/mpeg";break; 
                    //case "aif": str= "audio/x-aiff";break; 
                    //case "aiff": str= "audio/x-aiff";break; 
                    //case "aifc": str= "audio/x-aiff";break; 
                    //case "m3u": str= "audio/x-mpegurl";break; 
                    //case "ram": str= "audio/x-pn-realaudio";break; 
                    //case "rm": str= "audio/x-pn-realaudio";break; 
                    //case "rpm": str= "audio/x-pn-realaudio-plugin";break; 
                    //case "ra": str= "audio/x-realaudio";break; 
                    //case "wav": str= "audio/x-wav";break; 
                    //case "pdb": str= "chemical/x-pdb";break; 
                    //case "xyz": str= "chemical/x-xyz";break; 
                    //case "bmp": str= "image/bmp";break; 
                    //case "tiff": str= "image/tiff";break; 
                    //case "tif": str= "image/tiff";break; 
                    //case "djvu": str= "image/vnd.djvu";break; 
                    //case "djv": str= "image/vnd.djvu";break; 
                    //case "wbmp": str= "image/vnd.wap.wbmp";break; 
                    //case "ras": str= "image/x-cmu-raster";break; 
                    //case "pnm": str= "image/x-portable-anymap";break; 
                    //case "pbm": str= "image/x-portable-bitmap";break; 
                    //case "pgm": str= "image/x-portable-graymap";break; 
                    //case "ppm": str= "image/x-portable-pixmap";break; 
                    //case "rgb": str= "image/x-rgb";break; 
                    //case "xbm": str= "image/x-xbitmap";break; 
                    //case "xpm": str= "image/x-xpixmap";break; 
                    //case "xwd": str= "image/x-xwindowdump";break; 
                    //case "igs": str= "model/iges";break; 
                    //case "iges": str= "model/iges";break; 
                    //case "msh": str= "model/mesh";break; 
                    //case "mesh": str= "model/mesh";break; 
                    //case "silo": str= "model/mesh";break; 
                    //case "wrl": str= "model/vrml";break; 
                    //case "vrml": str= "model/vrml";break; 
                    //case "css": str= "text/css";break; 
                    //case "htm": str= "text/html";break; 
                    //case "asc": str= "text/plain";break; 
                    //case "rtx": str= "text/richtext";break; 
                    //case "rtf": str= "text/rtf";break; 
                    //case "sgml": str= "text/sgml";break; 
                    //case "sgm": str= "text/sgml";break; 
                    //case "tsv": str= "text/tab-separated-values";break; 
                    //case "wml": str= "text/vnd.wap.wml";break; 
                    //case "wmls": str= "text/vnd.wap.wmlscript";break; 
                    //case "etx": str= "text/x-setext";break; 
                    //case "xsl": str= "text/xml";break; 
                    //case "mpe": str= "video/mpeg";break; 
                    //case "qt": str= "video/quicktime";break; 
                    //case "mov": str= "video/quicktime";break; 
                    //case "mxu": str= "video/vnd.mpegurl";break; 
                    //case "avi": str= "video/x-msvideo";break;
                    //case "movie": str = "video/x-sgi-movie"; break;
                    //case "ice": str = "x-conference/x-cooltalk"; break;
                    #endregion
            }

            page.Response.ContentType = str;
            page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(savefilename + fileExt, System.Text.Encoding.UTF8));
            page.Response.BinaryWrite(bytes);
            page.Response.End();
            page.Response.Flush();

        }
        #endregion

        #region 导出excel

        public static string WriteExcel(DataTable ds, string path, string filename)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            //FileStream objFileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw = new StreamWriter(path + filename, false, Encoding.UTF8);
            try
            {

                StringBuilder strLine = new StringBuilder();
                for (int i = 0; i < ds.Columns.Count; i++)
                {
                    strLine.Append(ds.Columns[i].ColumnName.ToString() + Convert.ToChar(9));
                }
                strLine.Append(Environment.NewLine);
                for (int i = 0; i < ds.Rows.Count; i++)
                {
                    for (int j = 0; j < ds.Columns.Count; j++)
                    {
                        strLine.Append(ds.Rows[i][j].ToString() + "\t");
                    }
                    strLine.Append(Environment.NewLine);
                }
                sw.Write(strLine.ToString());
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                sw.Flush();
                sw.Close();
            }
        }

        public static void ExportDsToXls(HttpContextBase page, string fileName, string html)
        {

            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            page.Response.Clear();
            page.Response.Charset = "gb2312";
            page.Response.ContentType = "application/vnd.ms-excel";
            page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName) + ".xls");
            page.Response.Write("<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body>");

            page.Response.Write(html);

            page.Response.Write(tw.ToString());
            page.Response.Write("</body></html>");
            page.Response.End();
            hw.Close();
            hw.Flush();
            tw.Close();
            tw.Flush();
        }
        #endregion

        #region 判断是否是手机号
        public static bool IsTelMobile(string tel)
        {
            if (!string.IsNullOrEmpty(tel))
            {
                return Regex.IsMatch(tel, @"^1\d{10}$", RegexOptions.IgnoreCase);
            }
            return false;
        }
        #endregion


        //private const string method = "GET";
        //private const string appcode = "2f3d8030c66c4fb6b55bcd26eda99558";

        #region 获取IP地区
        public static string GetIPLocation(string IP)
        {
            try
            {
                string host = "https://dm-81.data.aliyun.com";
                string path = "/rest/160601/ip/getIpInfo.json";
                string querys = "ip=" + IP;
                string bodys = "";
                string url = host + path;
                HttpWebRequest httpRequest = null;
                HttpWebResponse httpResponse = null;
                if (0 < querys.Length)
                {
                    url = url + "?" + querys;
                }
                if (host.Contains("https://"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                }
                else
                {
                    httpRequest = (HttpWebRequest)WebRequest.Create(url);
                }
                httpRequest.Method = "GET";
                httpRequest.Headers.Add("Authorization", "APPCODE " + "f9ee276be1fa4a528edcaaca8a982a49");
                if (0 < bodys.Length)
                {
                    byte[] data = Encoding.UTF8.GetBytes(bodys);
                    using (Stream stream = httpRequest.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                Stream st = httpResponse.GetResponseStream();
                StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
                string jsonstr = reader.ReadToEnd();
                dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonstr);
                string IPLocation = "";
                if (json.code == 0)
                {
                    IPLocation = json.data.country + json.data.region + json.data.city + json.data.isp;
                }
                else
                {
                    IPLocation = json.data;
                }
                return IPLocation;
            }
            catch (Exception)
            {
                return "";
            }
        }
        public static bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
        #endregion

        #region 获取快递信息
        public static string GetEXPInfo(string kuaidiname, string no, out int status)
        {
            status = 0;
            try
            {
                string com = "";
                switch (kuaidiname)
                {
                    case "中通快递":
                        com = "zhongtong";
                        break;
                    case "顺丰速运":
                        com = "shunfeng";
                        break;
                    case "韵达快运":
                        com = "yunda";
                        break;
                    case "圆通速递":
                        com = "yuantong";
                        break;
                    case "申通快递":
                        com = "shentong";
                        break;
                    case "天天快递":
                        com = "tiantian";
                        break;
                    case "EMS":
                        com = "ems";
                        break;
                    case "中国邮政快递":
                        com = "pingyou";
                        break;
                    case "全峰快递":
                        com = "quanfeng";
                        break;
                    case "宅急送":
                        com = "zhaijisong";
                        break;
                    case "德邦物流":
                        com = "debang";
                        break;
                }
                if (string.IsNullOrWhiteSpace(com))
                {
                    return "获取物流信息失败";
                }
                string querys = "com=" + com + "&nu=" + no;
                string bodys = "";
                string url = "http://ali-deliver.showapi.com/showapi_expInfo";
                System.Net.HttpWebRequest httpRequest = null;
                System.Net.HttpWebResponse httpResponse = null;
                url = url + "?" + querys;
                httpRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                httpRequest.Method = "GET";
                httpRequest.Headers.Add("Authorization", "APPCODE " + "2f3d8030c66c4fb6b55bcd26eda99558");
                if (0 < bodys.Length)
                {
                    byte[] data = Encoding.UTF8.GetBytes(bodys);
                    using (System.IO.Stream stream = httpRequest.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
                httpResponse = (System.Net.HttpWebResponse)httpRequest.GetResponse();
                System.IO.Stream st = httpResponse.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(st, Encoding.GetEncoding("utf-8"));
                string jsonstr = reader.ReadToEnd();
                dynamic expdata = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonstr);
                if (expdata.showapi_res_code == 0)
                {
                    status = expdata.showapi_res_body.status; //-1 待查询 0 查询异常 1 暂无记录 2 在途中 3 派送中 4 已签收 5 用户拒签 6 疑难件 7 无效单 8 超时单 9 签收失败 10 退回
                    return Newtonsoft.Json.JsonConvert.SerializeObject(expdata.showapi_res_body);
                }
                else
                {
                    return "获取物流信息失败";
                }
            }
            catch (Exception)
            {
                return "获取物流信息失败";
            }
        }
        #endregion

        #region 发送短信
        //public static void fasongduanxin(string qyname, string tel, string TemplateID, string json)
        //{
        //    ITopClient client = new DefaultTopClient("http://gw.api.taobao.com/router/rest", "23431642", "59823762c232cc296db77db23783fa8f");
        //    AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        //    req.Extend = "";
        //    req.SmsType = "normal";
        //    req.SmsFreeSignName = qyname;
        //    req.SmsTemplateCode = TemplateID;
        //    if (!string.IsNullOrWhiteSpace(json))
        //    {
        //        req.SmsParam = json;
        //    }
        //    req.RecNum = tel;
        //    AlibabaAliqinFcSmsNumSendResponse rsp = client.Execute(req);
        //}
        #endregion

        #region 获取域名
        public static string GetDomainName()
        {
            string url = HttpContext.Current.Request.Url.Host;
            if (url.ToLower().StartsWith("http://"))
            {
                url = url.Substring(7);
            }
            if (url.LastIndexOf("/") == -1)
            {
                url += "/";
            }

            return "http://" + url;

        }
        #endregion

        #region string转int[]
        public static int[] StringToInts(string input, char split = ',')
        {
            var list = input.Split(split);
            int[] ids = new int[list.Length];
            for (var v = 0; v < list.Length; v++)
            {
                int I = Int32.Parse(list[v]);
                ids[v] = I;
                v++;
            }
            return ids;
        }
        #endregion

        #region 发短信接口
        public static void SendSMS(string tel, string code, string SmsParam = "")
        {
            try
            {
                ITopClient client = new DefaultTopClient("http://gw.api.taobao.com/router/rest", "23431642", "59823762c232cc296db77db23783fa8f");
                AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
                req.Extend = "";
                req.SmsType = "normal";
                req.SmsFreeSignName = "飓速网";
                if (!string.IsNullOrWhiteSpace(SmsParam))
                {
                    req.SmsParam = SmsParam;
                }
                req.SmsTemplateCode = code;
                req.RecNum = tel;
                AlibabaAliqinFcSmsNumSendResponse rsp = client.Execute(req);

            }
            catch (Exception)
            {

            }
        }

        #endregion

        #region 字符串URL编码
        public static string UrlEncode(string temp, Encoding encoding)
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach (char ch in temp)
            {
                string t = ch.ToString();
                string k = HttpUtility.UrlEncode(t, encoding);
                if (t == k)
                {
                    stringBuilder.Append(t);
                }
                else
                {
                    stringBuilder.Append(k.ToUpper());
                }
            }
            return stringBuilder.ToString().Replace("+", "%20").Replace("*", "%2A").Replace("%7E", "~");
        }
        #endregion

        #region 获取文件MD5值
        public static string GetMD5HashFromFile(string fileName)
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }

            }
            catch (Exception ex)
            {
                //throw new Exception("GetMD5HashFromFile() fail, error" +ex.Message);
            }
            return sb.ToString();
        }
        #endregion


    }
}
